package com.example.ticket.service.impl;

import com.example.ticket.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class MailServiceimpl implements MailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.from}")
    private String from;


/*    @RabbitListener(bindings = @QueueBinding(value =@Queue("fanout_queue_email") ,
            exchange = @Exchange(value = "fanout_exchange",type = "fanout")))*/
    @Override
    @Async
    public void sendHtmlMail(String to,String subject,String content) {
        long start=System.currentTimeMillis();
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            //我的邮箱发过去
            helper.setFrom(from);
            //收件人邮箱
            helper.setTo(to);
            //邮件标题
            helper.setSubject(subject);
            //内容
            helper.setText(content, true);
            mailSender.send(message);
            long end=System.currentTimeMillis();
            //日志信息
            logger.info("邮件已经发送,耗时:"+(end-start));
        } catch (MessagingException e) {
            logger.error("发送邮件时发生异常");
        }
    }
}
